# -*- coding: utf-8 -*-
import json
import logging
from hashlib import md5

from django.http import HttpResponse
from django.utils.decorators import method_decorator
from django.utils.encoding import smart_unicode
from django.views.decorators.http import require_GET, require_POST
from django.views.generic import TemplateView
from future.utils import raise_with_traceback

from common.cache import redis_cache
from common.recharge import db as recharge_db
from common.recharge import handler
from common.recharge.model import *
from common.utils import exceptions as err
from common.utils.api import token_required
from common.utils.decorator import response_wrapper
from common.utils.respcode import StatusCode
from common.utils import track_logging
from common.recharge import handler as recharge_handler
from common.pay.handler import pay_after_recharge
from common.withdraw.unionagency_withdraw import generate_sign, API_KEY

_LOGGER = track_logging.getLogger(__name__)


@require_GET
@response_wrapper
@token_required
def get_apply_records(request):
    """
    查看记录
    """
    user_id = request.user_id
    try:
        page = int(request.GET.get('page', 0))
        size = int(request.GET.get('size', 0))
    except Exception as e:
        raise_with_traceback(err.ParamError(e))

    r_list = handler.get_user_applys(user_id, page, size)
    data = {
        'list': r_list
    }
    return data


@require_GET
@response_wrapper
def get_rechargees(request):
    """
    查看方式
    """
    wechat_items = redis_cache.get_recharge_wechat_assign_count()
    rechargee_info = RECHARGEE_INFO
    update_items = [json.loads(item) for item in wechat_items]
    rechargee_info.update({3: update_items})
    data = {
        'rechargees': rechargee_info
    }
    return data


@require_POST
@response_wrapper
@token_required
def submit(request):
    try:
        data = smart_unicode(request.body)
        info = json.loads(data)
        recharge_type = int(info['recharge_type'])
        recharger_info = info['recharger_info']
        rechargee_info = info['rechargee_info']
    except ValueError as e:
        raise err.ParamError('request body is not valid json.(%s)' % e)

    if recharge_db.exist_submit_apply(request.user_id, recharge_type):
        raise err.DataError('unresolved exists', status=StatusCode.REACH_LIMIT)

    handler.apply_recharge(request.user_id, recharge_type, recharger_info, rechargee_info)
    return {}


@require_POST
@response_wrapper
def callback(request):
    try:
        trade_no = request.POST.get('trade_no')
        amount = request.POST.get('amount')
        remark = request.POST.get('remark')
        pay_time = request.POST.get('pay_time')
        sign = request.POST.get('sign')
    except Exception as e:
        raise_with_traceback(err.ParamError(e))

    _LOGGER.info('alipay recharge callback, received, %s', request.POST)
    # check sign
    sign_str = u'amount={}&pay_time={}&remark={}&trade_no={}{}'.format(
        amount, pay_time, remark, trade_no, ALIPAY_TRANS_KEY)
    m = md5()
    m.update(sign_str.encode('utf8'))
    calc_sign = m.hexdigest()
    if sign != calc_sign:
        _LOGGER.warn('alipay recharge callback, wrong sign with trade_no:%s', trade_no)
        raise err.ParamError('wrong sign')

    handler.submit_alipay_trans(trade_no, remark, amount, pay_time)
    return HttpResponse('SUCCESS', status=200)


class RechargeWechatView(TemplateView):

    def post(self, request):
        data = json.loads(smart_unicode(request.body))

        item_list = data.get("online_agency_list")
        if not item_list:
            redis_cache.delete_recharge_wechat()
        else:
            update_list = []
            for item in item_list:
                info = dict(name=item['nick_name'], wechat_no=item['weixin'], qrcode=item['qrcode'])
                update_list.append(json.dumps(info, ensure_ascii=False))
            _LOGGER.info("update list {}".format(update_list))
            redis_cache.delete_recharge_wechat()
            redis_cache.set_recharge_wechat(*update_list)
        return {}

    @method_decorator(response_wrapper)
    def dispatch(self, *args, **kwargs):
        return super(RechargeWechatView, self).dispatch(*args, **kwargs)


class RechargeView(TemplateView):
    def post(self, req):
        data = json.loads(smart_unicode(req.body))
        user_id = int(data['player_id'])
        amount = float(data['amount'])
        agency_id = data['agency_id']
        platform_pay_id = int(data['platform_pay_id'])
        recharge_type = RECHARGE_TYPE.WECHATPAY
        recharger_info = dict(price=amount)
        rechargee_info = dict(agency_id=agency_id, platform_pay_id=platform_pay_id)

        if not redis_cache.set_pay_params(user_id, platform_pay_id):
            raise err.AuthenticateError(u'重复请求')

        recharge = recharge_handler.apply_recharge(user_id, recharge_type, recharger_info, rechargee_info)
        return dict(status='ok', pay_id=recharge.pay_id)

    @method_decorator(response_wrapper)
    def dispatch(self, *args, **kwargs):
        return super(RechargeView, self).dispatch(*args, **kwargs)


class SingleRechargeView(TemplateView):
    def post(self, req):
        data = json.loads(smart_unicode(req.body))
        platform_pay_id = data['platform_pay_id']
        amount = float(data['amount'])
        user_id = int(data['player_id'])
        pay_id = data['pay_id']
        agency_id = data['agency_id']
        sign = data.pop('sign')

        if not redis_cache.set_pay_params(user_id, sign):
            raise err.AuthenticateError(u'重复请求')

        if sign != generate_sign(data, API_KEY):
            raise err.AuthenticateError(u'签名不合法')

        recharge_handler.finish_wechat_apply(user_id, pay_id, amount, agency_id)

        return dict(status='ok', pay_id=pay_id)

    @method_decorator(response_wrapper)
    def dispatch(self, *args, **kwargs):
        return super(SingleRechargeView, self).dispatch(*args, **kwargs)
